import { useRef, useEffect } from "react";
import logo from "@/assets/img/logo.png";
import { Button, Popover, Menu, Message } from "@arco-design/web-react";
import { BotMessageSquare, ClipboardList, ShoppingBag } from "lucide-react";

import { useNavigate } from "react-router-dom";
import LoginDialog from "@/components/LoginDialog";
import { useSelector, useDispatch } from "react-redux";
import { setCountBalance, setUserInfo } from "@/store/home/homeSlice";
import ChatApi from "@/api/chat/chat-api";
import UserApi from "@/api/user/user-api";
import currencyIcon from "@/assets/img/navMenu/currency.svg";
import { formatAmount } from "@/lib/utils";
import jsCookie from "js-cookie";

import styles from "./index.module.less";
const MenuItem = Menu.Item;

const NavMenu = () => {
  const userApi = new UserApi();
  const loginDialogRef = useRef<any>(null);
  const navigate = useNavigate();
  const userInfo = useSelector((state: any) => state.home.userInfo);
  const countBalance = useSelector((state: any) => state.home.countBalance);

  const dispatch = useDispatch();
  // 新的聊天
  const handleCreateChat = () => {
    createOrUpdateSessionRecordFn();
  };

  // 返回首页
  const backHome = () => {
    navigate(`/`);
  };

  // 登录
  const handleLogin = () => {
    loginDialogRef.current.getPage();
  };

  // 聊天历史
  const handlerChatHistory = () => {
    navigate(`chatHistory`);
  };

  // 订阅
  const handlerSubscription = () => {
    navigate(`subscription`);
  };

  // 获取用户余额
  const getUserBalanceFn = async () => {
    try {
      let res = await userApi.getUserBalance();
      if (res.code === 200) {
        let resData = res.result;
        console.log(resData, "cccccccccc");
        dispatch(setCountBalance(resData.countBalance));
      } else {
        console.log(res);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 创建会话
  const createOrUpdateSessionRecordFn = async () => {
    try {
      let res = await ChatApi.createOrUpdateSessionRecord({
        requestId: "",
        name: "未命名会话",
      });
      if (res.code === 200) {
        let requestId = res.result;
        navigate(`/chat/${requestId}`);
      }
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  };

  const removeCookie = (name: string) => {
    jsCookie.remove(name);
  };

  // 退出登录
  const logoutFn = async () => {
    // 清空cookie中的satoken
    removeCookie("satoken");
    // 清空用户信息

    dispatch(setCountBalance(0));
    dispatch(setUserInfo(null));
    Message.success("退出登录成功");
  };

  useEffect(() => {
    getUserBalanceFn();
  }, []);
  return (
    <div className={styles.navMenuWarp}>
      <div onClick={backHome} className="menu_item-logo">
        <img className="logo" src={logo} alt="" />
      </div>

      <div className="menu_item-devider"></div>

      <div className="menu_item-btn">
        <Button
          onClick={handleCreateChat}
          shape="circle"
          size="large"
          type="text"
          icon={
            <BotMessageSquare
              strokeWidth={1.25}
              className="menu_item-btn-icon"
            />
          }
        ></Button>
      </div>

      <div className="menu_item-btn">
        <Button
          onClick={handlerChatHistory}
          shape="circle"
          size="large"
          type="text"
          icon={
            <ClipboardList strokeWidth={1.25} className="menu_item-btn-icon" />
          }
        ></Button>
      </div>

      <div className="menu_item-btn">
        {/* 订阅 */}
        <Button
          onClick={handlerSubscription}
          shape="circle"
          size="large"
          type="text"
          icon={
            <ShoppingBag strokeWidth={1.25} className="menu_item-btn-icon" />
          }
        ></Button>
      </div>

      {!userInfo ? (
        <div
          className="menu_item-user hover:scale-[1.1] transition-all duration-300"
          onClick={handleLogin}
        >
          登录
        </div>
      ) : (
        <div className="useInfoBox">
          <div className="count">
            <img className="currencyIcon" src={currencyIcon} alt="" />
            {formatAmount(countBalance)}
          </div>

          <Popover
            trigger="click"
            position="right"
            content={
              <Menu>
                <MenuItem key="1" onClick={logoutFn}>
                  退出登录
                </MenuItem>
              </Menu>
            }
          >
            <img className="logo" src={userInfo?.avatar} alt="" />
          </Popover>
        </div>
      )}

      <LoginDialog ref={loginDialogRef} />
    </div>
  );
};

export default NavMenu;
